package com.freejava.jdbctest.dao;


import com.freejava.jdbctest.entities.Article;
import com.freejava.jdbctest.entities.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

@Repository
public class ArticleDao {
    @Autowired
    JdbcTemplate jdbcTemplate;

    // 获取文章
    public List<Article> getAll() {
        return jdbcTemplate.query("select * from my_articles", new BeanPropertyRowMapper<>(Article.class));
    }

    // 新增一篇文章
    public int add(Article article) {
        return jdbcTemplate.update("INSERT INTO my_articles (title, author, content, category_id, tags, is_deleted, created) values(?, ?, ?, ?, ?, ?, ?)", article.getTitle(), article.getAuthor(), article.getContent(), article.getCategoryId(), article.getTags(), article.getCreated());
    }

    // 获取单篇文章的数据
    public Article getArticleById(int id) {
        return jdbcTemplate.queryForObject("select * from my_articles where id=?", new BeanPropertyRowMapper<>(Article.class), id);
    }

    // 更新文章信息
    public int update(Article article) {
        return jdbcTemplate.update("UPDATE my_articles set title=?, author=? WHERE id=?", article.getTitle(), article.getAuthor(), article.getId());
    }


    // 批量更新书籍
    public int[] updateBatch(List<Article> articles) {
        return jdbcTemplate.batchUpdate("UPDATE books set title=?, price=? WHERE id =?", new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                Article article = articles.get(i);
                ps.setString(1, article.getTitle());
                ps.setString(2, article.getAuthor());
                ps.setInt(3, article.getId());

            }

            @Override
            public int getBatchSize() {
                return articles.size();
            }
        });
    }

}
